package com.zzty.springmybatis.common;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ZipReader {
	public static JSONArray readZipFile(String file) throws Exception {

		System.out.println("read in");
		ZipFile zf = new ZipFile(new File(file));
		long timestamp = 0;
		final int maxsize = 10;
		LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
		ExecutorService executor = new ThreadPoolExecutor(maxsize, maxsize, 0l, TimeUnit.MILLISECONDS, queue);
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		ZipInputStream zin = new ZipInputStream(in);
		ZipEntry ze;
		
		JSONArray jsonarray = new JSONArray();
		for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
			JSONObject jsonobject = new JSONObject();
			ze = ((ZipEntry) entries.nextElement());
			if (ze.isDirectory()) {
				System.out.println("is directory");
			} else {
				 System.err.println("file - " + ze.getName() + " : " +
				 ze.getSize() + " bytes");
				long size = ze.getSize();
				if (size > 0) {
					BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(ze), "UTF-8"));
					String line;
					int row = 0;
					jsonobject.put(row, ze.getName());
					while ((line = br.readLine()) != null) {

						++row;
						jsonobject.put(row, line);
					}
					br.close();
				}
			}
			jsonarray.add(jsonobject);

		}
		zin.closeEntry();
		return jsonarray;
	}
}